import flash.net.FileReference;

var clickedId:String;
var items:Array;
var itemsCache:Object;
var searchObj:Object;	//currentPage, totalPage, keyword
var SINGLE_PAGE:Number=12;
var fileRef:FileReference;

function init(param, data, slot)
{
	Packages.system.Platform.renderPortlet(slot);
	items=new Array();
	itemsCache=new Object();
	searchObj=new Object();
	search();
}

function clearKeyword(param:String, data, slot:String) 
{
	var keywordInput=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "keywordInput"); 
	keywordInput.htmlText="";
}

function search(param:String, data, slot:String)
{
	if (data.keyword==searchObj.keyword&&data.keyword!=""&&data.keyword!=null&&data.currentPage==null) 
		return;	

	var keyword=data.keyword!=null?data.keyword:"";
	if (data.currentPage==null) calcPage(keyword);
	searchObj.keyword=keyword;ReadingBrowser
	var keywordDisplay=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "keywordDisplay");
	keywordDisplay.htmlText=keyword;

	if (items.length>0)
	{
		clearItems();
		items=new Array();
	}

	var item=new Object();
	item.type="search";
	item.param=new Object();
	item.param.keyword=keyword;
	item.param.type=1;
	item.param.index=(searchObj.currentPage-1)*SINGLE_PAGE;
	item.param.length=SINGLE_PAGE;
	item.result=new Object();
	item.result.owner=this;
	//for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
	item.result.onResult=function(res)
	{
		trace("onResult.obj.returnObj: "+res.returnObj.length);
		for (var a=0; a<res.returnObj.length; a++)
		{
			var rObj:Object=new Object();
			rObj.type="reading";
			rObj.content=new Object();
			rObj.content.id=res.returnObj[a].id;
			rObj.content.uuid=res.returnObj[a].uuid;
			rObj.content.bookName=res.returnObj[a].bookName;
			rObj.content.authorName=res.returnObj[a].bookAuthor;
			rObj.content.readerName=res.returnObj[a].recorder;
			rObj.content.audioDuration=Packages.system.Util.time2String(Number(res.returnObj[a].duration), "MM:SS");
			rObj.content.bookUuid=res.returnObj[a].bookUuid;
			//for (var b in rObj.content) trace("rObj.content."+b+":"+rObj.content[b]);
			addItem(rObj);
		}
	}	
	Packages.system.MLF.rtmpCaller(item);
}

function displayItemPortlet(cont:String)
{
	mlf.gatekeeper.native.Caller.MLoader(null, null, null, null, cont);
}

function clickItem(param:String, data, slot:String)
{
	//trace("clickItem.param..."+param);
	var id=param.substring(param.indexOf("bg_")+3);
	var bg=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "bg_"+id);
	bg._alpha=100;
	Packages.system.Platform.highlightBlock(bg);

	if (clickedId!=null&&clickedId!=id)
	{
		bg=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "bg_"+clickedId);
		bg._alpha=0;
	}
	clickedId=id;
}

function addItem(item:Object)
{
	//Add an uploaded resource into Book List
	items.push(item.content.id);
	itemsCache[item.content.id]=item.content;
	if (item.type=="reading")
	{
		displayItemPortlet(Packages.modula.ReadingQuery.getReadingItem(item.content));
	}
}

function clearItems()
{
	//trace("clearItems");
	var itemStr=items.pop();
	while (itemStr!=null)
	{
		trace("itemStr:"+itemStr);
		var item=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "item_"+itemStr);
		if (item!=null) 
		{
			item.unloadMovie();
			item.removeMovieClip();	
			mlf.mcmanager.component.IndexSlot.removeElement("ReadingBrowser", "item_"+itemStr); 
			itemsCache[itemStr]=null;
		}
		itemStr=items.pop();
	}
}

function calcPage(keyword:String)
{
	if (keyword!=searchObj.keyword||searchObj.totalPage==null)
	{
		var item=new Object();
		item.type="count";
		item.param=new Object();
		item.param.keyword=keyword!=null?keyword:"";
		item.param.type=1;
		item.result=new Object();
		item.result.owner=this;
		for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
		item.result.onResult=function(res)
		{
			trace("count.onResult.obj.returnObj: "+res.returnObj);
			//this.owner.clearItems();
			if (res.returnObj!=null)
			{
				var totalPage=Math.ceil(res.returnObj/SINGLE_PAGE);
				searchObj.totalPage=totalPage;
				var tp=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "totalPage");
				tp.htmlText=searchObj.totalPage;
			}
		}	
		Packages.system.MLF.rtmpCaller(item);	
		
		searchObj.currentPage=1;
		var cp=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "currentPage");
		cp.htmlText=searchObj.currentPage;
	}
}

function nextPage()
{
	if (searchObj.currentPage+1<=searchObj.totalPage)
	{ 	
		searchObj.currentPage++;
		search(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function prevPage()
{
	if (searchObj.currentPage>1) 
	{
		searchObj.currentPage--;
		search(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function firstPage()
{
	if (searchObj.currentPage!=1)
	{
		searchObj.currentPage=1;
		search(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function lastPage()
{
	if (searchObj.currentPage!=searchObj.totalPage)
	{
		searchObj.currentPage=searchObj.totalPage;
		search(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function playReading(param:String, data, slot:String)
{
	var id=parseIconName(param);
	
	var item=new Object();
	item.type="getDeployInfo";
	item.param=new Object();
	item.param.readingUuid=itemsCache[id].uuid;
	item.result=new Object();
	item.result.owner=this;
	//for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
	item.result.onResult=function(res)
	{
		trace("onResult.obj.returnObj: "+res.returnObj.length);
		for (var a in res.returnObj)
		{
			//for (var b in res.returnObj[a]) trace("res:"+b+"="+res.returnObj[a][b]);
			if (res.returnObj[a].deployType=="mp3/unpackaged")
			{
				var deployUuid=res.returnObj[a].uuid;
				trace("playReading...name:"+itemsCache[id].bookName+" sync:"+deployUuid);
				Packages.components.ReadingPlayer.addPlayItem({name:itemsCache[id].bookName, 
					sync:Packages.system.Util.getHttpBaseUrl()+"/download?uuid="+deployUuid+"&type=2&subtype=1000"}); 

				
				var content=itemsCache[id].bookName+Packages.system.MLF.scanDictionary(mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "main"), "addedIntoPlayList");
				Packages.system.Platform.messageHint("ReadingBrowser", content, "hint");
			} 
		}
	}	
	Packages.system.MLF.rtmpCaller(item);	

}

function recordReading(param:String, data, slot:String)
{}

function downloadText(param:String, data, slot:String)
{
	//trace("param:"+param+" data:"+data+" slot:"+slot);
	var id=parseIconName(param);
	var url=Packages.system.Util.getHttpBaseUrl()+"/download?type=0&subtype=0&uuid="
		+itemsCache[id].bookUuid;
	trace("downloadText...url:"+url);
	var filename=itemsCache[id].bookName+".txt";
	doFileDownload(url, filename);
}

function downloadMp3(param:String, data, slot:String)
{
	var id=parseIconName(param);
	var url=Packages.system.Util.getHttpBaseUrl()+"/download?type=1&subtype=1&uuid="
		+itemsCache[id].uuid;
	trace("downloadMp3...url:"+url);
	var filename=itemsCache[id].bookName+".mp3";
	doFileDownload(url, filename);
}

function downloadMobile(param:String, data, slot:String)
{
	var id=parseIconName(param);

	var item=new Object();
	item.type="getDeployInfo";
	item.param=new Object();
	item.param.readingUuid=itemsCache[id].uuid;
	item.result=new Object();
	item.result.owner=this;
	//for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
	item.result.onResult=function(res)
	{
		trace("onResult.obj.returnObj: "+res.returnObj.length);
		for (var a in res.returnObj)
		{
			//for (var b in res.returnObj[a]) trace("res:"+b+"="+res.returnObj[a][b]);
			if (res.returnObj[a].deployType=="swf/packaged")
			{
				var deployUuid=res.returnObj[a].uuid;
				var url=Packages.system.Util.getHttpBaseUrl()+"/download?type=2&subtype=1001&uuid="
					+deployUuid;
				trace("downloadMobile...url:"+url);
				var filename=itemsCache[id].bookName+".zip";
				doFileDownload(url, filename);	
			} 
		}
	}	
	Packages.system.MLF.rtmpCaller(item);		
}

function doFileDownload(url:String, filename:String)
{
	fileRef=new FileReference();
	var listener:Object=new Object();
	listener.owner=this;
	listener.onProgress=function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void  {
		trace("bytesLoaded:"+bytesLoaded+" bytesTotal:"+bytesTotal);
		var progress:String = Math.floor(bytesLoaded/bytesTotal*100)+"%";
		//trace("onProgress ... "+progress);
		var content=Packages.system.MLF.scanDictionary(mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "main"), "Download Progress");
		Packages.system.Platform.messageHint("ReadingBrowser", content+progress, "hint");
	};
	
	listener.onComplete = function(file:FileReference):Void  {
		trace("onComplete ...");
		file.removeListener(listener);
		var content=Packages.system.MLF.scanDictionary(mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "main"), "Download Complete");
		Packages.system.Platform.messageHint("ReadingBrowser", content, "hint");
	};

	listener.onHTTPError = function(file:FileReference, httpError:Number):Void  {
		trace("onHTTPError ...");
		file.removeListener(listener);
		var content=Packages.system.MLF.scanDictionary(mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "main"), "Download onHTTPError");
		Packages.system.Platform.messageHint("ReadingBrowser", content, "warning");
	};

	listener.onIOError = function(file:FileReference):Void  {
		trace("onIOError ...");
		file.removeListener(listener);
		var content=Packages.system.MLF.scanDictionary(mlf.gatekeeper.native.Caller.scanElement("ReadingBrowser", "main"), "Download onIOError");
		Packages.system.Platform.messageHint("ReadingBrowser", content, "warning");
	};	

	fileRef.addListener(listener);
	fileRef.download(url, filename);	
}

function parseIconName(param:String):String
{
	//param:_root-ReadingBrowser-main-rportlet-container-item_115-text#115-media_text#115-text
	if (param!=null)
	{
		var mediaArr:Array=param.split("#");
		var mediaStr:String=mediaArr[1];
		var idArr:Array=mediaStr.split("-");
		return idArr[0];
	}
}

function hintOn(param, data, slot)
{
	//trace("hint on..param:"+param);
	var op:String;
	if (param.indexOf("media_rplay")>-1)
	{
		op="rplay";
	}	
	//else if (param.indexOf("media_record")>-1)
	//{
	//	op="record";
	//}
	else if (param.indexOf("media_text")>-1)
	{
		op="text";
	}
	else if (param.indexOf("media_mp3")>-1)
	{
		op="mp3";
	}
	else if (param.indexOf("media_mobile")>-1)
	{
		op="mobile";
	}
	Packages.system.Platform.displayHint(op, data, slot);
}

function hintOff(param, data, slot)
{
	//trace("hint off..param:"+param);
	Packages.system.Platform.disposeHint(param, data, slot);
}